//
//  DINGStatusPictureView.swift
//  0730Microblog
//
//  Created by ding on 15/8/8.
//  Copyright © 2015年 ding. All rights reserved.
//

import UIKit
import SDWebImage

class DINGStatusPictureView: UICollectionView {
    
    private let flowLayout = UICollectionViewFlowLayout()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
        backgroundColor = UIColor.lightTextColor()
        self.dataSource = self
        registerClass(DINGPictureCell.self, forCellWithReuseIdentifier: cellReusedIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var statuses: DINGMicroblogStatus? {
        didSet {
            sizeToFit()
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calculatePictureViewSize()
    }
    
    
    func calculatePictureViewSize() -> CGSize {
        var result = CGSizeMake(100, 100)
        flowLayout.itemSize = result
        let pictureCount = statuses?.pictureURLs?.count ?? 0
        let margin = CGFloat(10)
        
        switch pictureCount {
        case 1:
            let keyDict = statuses?.pictureURLs?.last
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(keyDict!["thumbnail_pic"]) {
                
                result = image.size
                result.width = (result.width < 40) ? 40 : result.width
                result.width = (result.width > UIScreen.mainScreen().bounds.width) ? 100 : result.width
                flowLayout.itemSize = result
            }
            
//            print(image.size)
            // 有可能image缓存失败， 那么必须要指定一个默认大小
            
        case 4:
            result = CGSizeMake(result.width * 2 + margin, result.height * 2 + margin)
        case 9:
            result = CGSizeMake(result.width * 3 + margin * 2, result.height * 3 + margin * 2)
        case 2, 3, 5, 6, 7, 8:
            let row = (pictureCount % 3 != 0) ? CGFloat(1 + pictureCount / 3) : CGFloat(pictureCount / 3)
            let column = CGFloat((pictureCount / 3 > 0) ? 3 : (pictureCount % 3))
            result = CGSizeMake(result.width * column + margin * (column - 1), result.height * row + margin * (row - 1))
            
        default: result = CGSizeZero
            
        }
        
        return result
    }
    
}

private let cellReusedIdentifier = "picture_cell"
extension DINGStatusPictureView:UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        print(statuses?.pic_urls?.count)
//        print("1234561231\(statuses?.pictureURLs?.count)")
        return statuses?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellReusedIdentifier, forIndexPath: indexPath) as! DINGPictureCell
        cell.backgroundColor = UIColor.blackColor()
        cell.pictureUrlDict = statuses?.pictureURLs![indexPath.item]

        return cell
    }
}

class DINGPictureCell: UICollectionViewCell {
    
    private var pictureUrlDict: [String : String]? {
        didSet {
//            print(pictureUrlDict)
            
            if let pictureUrlString = pictureUrlDict!["thumbnail_pic"] {
                let picUrl = NSURL(string: pictureUrlString)
                // 网络下载显示图片
//                print("网络显示图片")
                imgView.sd_setImageWithURL(picUrl)
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupPictureCellUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupPictureCellUI() {
        contentView.addSubview(imgView)
        
        // 自动布局
        imgView.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[targetView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["targetView" : imgView]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[targetView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["targetView" : imgView]))
    }
    
    private lazy var imgView: UIImageView = {
        let v = UIImageView()
        v.contentMode = UIViewContentMode.ScaleAspectFill
        
        v.clipsToBounds = true
        return v
    }()
}
